<template>
	<van-action-sheet
		v-model:show="visible"
		title="用户信息收集表"
		:closeable="false"
		:close-on-click-overlay="false"
		@opened="drawerOpened"
	>
		<div id="amisHtml"></div>
	</van-action-sheet>
</template>

<script setup>
import 'amis/lib/themes/default.css';
import { ref, watch, computed, inject } from 'vue'
import { useStore } from 'vuex'
import useUtils from "@/hooks/useUtils.js";

const api = inject('api')
const store = useStore()
const visible = ref(false)
const detail = computed(() => store.state.live.detail)
watch(() => store.state.live.detail, val => {
	
	if (val.id) {
		/**
		 * 判断是否展示表单收集信息
		 * 1：live对象的hasCollectAudienceMsg 表示是否已经收集信息，如果为true，直接不展示收集信息表单
		 * 2：接上一步，如果hasCollectAudienceMsg返回false，看live对象的projectVo,collectAudienceMsg字段，如果为false，直接不展示收集信息表单，如果为true，展示收集信息表单
		 */
		if (!val.hasCollectAudienceMsg && val.projectVo?.collectAudienceMsg) {
			visible.value = true
		} else {
			submitAudForm()
		}
	}
})

function submitAudForm() {
	let data = {
		liveId: detail.value.id,
		projectId: detail.value.projectId,
		auid: useUtils().getOpenid()
	}
	api.saveAudienceForm(data).then(res => {
		if(res.code === 0) {
			store.commit('live/SET_IM', {
				imId: res.data
			})
		}
	})
}

window.submitCollectSucc = function () {
	console.log('amis提交成功')
	const imId = localStorage.getItem('imId')
	visible.value = false
	store.commit('live/SET_IM', {
		imId: imId
	})
}

function drawerOpened () {
	api.getProjectAmisForm(detail.value.projectId).then(res => {
		if(res.code === 0) { 
			const amis = amisRequire('amis/embed');
			const baseUrl = import.meta.env.VITE_BASE_URL;
			const formJson = res.data.formJson;
			const formData = JSON.parse(formJson.replaceAll('${baseUrl}', baseUrl))
			amis.embed('#amisHtml', formData);
		}
		
	})
}

</script>

<style scoped>

</style>
